home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1997 April / macformat-049.iso / mac / Shareware Plus / Developers / dropg++ / usr / src / loader / myalloc.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-08-23  |  11.1 KB  |  415 lines  |  [TEXT/KAHL]

  1. /*
  2.  * Copyright (c) 1983 Regents of the University of California.
  3.  * All rights reserved.
  4.  *
  5.  * Redistribution and use in source and binary forms, with or without
  6.  * modification, are permitted provided that the following conditions
  7.  * are met:
  8.  * 1. Redistributions of source code must retain the above copyright
  9.  *    notice, this list of conditions and the following disclaimer.
  10.  * 2. Redistributions in binary form must reproduce the above copyright
  11.  *    notice, this list of conditions and the following disclaimer in the
  12.  *    documentation and/or other materials provided with the distribution.
  13.  * 3. All advertising materials mentioning features or use of this software
  14.  *    must display the following acknowledgement:
  15.  *    This product includes software developed by the University of
  16.  *    California, Berkeley and its contributors.
  17.  * 4. Neither the name of the University nor the names of its contributors
  18.  *    may be used to endorse or promote products derived from this software
  19.  *    without specific prior written permission.
  20.  *
  21.  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  22.  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  23.  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  24.  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  25.  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  26.  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  27.  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  28.  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  29.  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  30.  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31.  * SUCH DAMAGE.
  32.  */
  33.  
  34. #if defined(LIBC_SCCS) && !defined(lint)
  35. static char sccsid[] = "@(#)malloc.c    5.11 (Berkeley) 2/23/91";
  36. #endif /* LIBC_SCCS and not lint */
  37.  
  38. /*
  39.  * malloc.c (Caltech) 2/21/82
  40.  * Chris Kingsley, kingsley@cit-20.
  41.  *
  42.  * This is a very fast storage allocator.  It allocates blocks of a small 
  43.  * number of different sizes, and keeps free lists of each size.  Blocks that
  44.  * don't exactly fit are passed up to the next larger size.  In this 
  45.  * implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long.
  46.  * This is designed for use in a virtual memory environment.
  47.  */
  48.  
  49. #include <sys/types.h>
  50. #include <stdlib.h>
  51. #include <string.h>
  52. #include <unistd.h>
  53.  
  54. #ifndef NULL
  55. #define    NULL 0
  56. #endif
  57.  
  58. static void morecore();
  59. static int findbucket();
  60.  
  61. /*
  62.  * The overhead on a block is at least 4 bytes.  When free, this space
  63.  * contains a pointer to the next free block, and the bottom two bits must
  64.  * be zero.  When in use, the first byte is set to MAGIC, and the second
  65.  * byte is the size index.  The remaining bytes are for alignment.
  66.  * If range checking is enabled then a second word holds the size of the
  67.  * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC).
  68.  * The order of elements is critical: ov_magic must overlay the low order
  69.  * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern.
  70.  */
  71. union    overhead {
  72.     union    overhead *ov_next;    /* when free */
  73.     struct {
  74.         u_char    ovu_magic;    /* magic number */
  75.         u_char    ovu_index;    /* bucket # */
  76. #ifdef RCHECK
  77.         u_short    ovu_rmagic;    /* range magic number */
  78.         u_int    ovu_size;    /* actual block size */
  79. #endif
  80.     } ovu;
  81. #define    ov_magic    ovu.ovu_magic
  82. #define    ov_index    ovu.ovu_index
  83. #define    ov_rmagic    ovu.ovu_rmagic
  84. #define    ov_size        ovu.ovu_size
  85. };
  86.  
  87. #define    MAGIC        0xef        /* magic # on accounting info */
  88. #define RMAGIC        0x5555        /* magic # on range info */
  89.  
  90. #ifdef RCHECK
  91. #define    RSLOP        sizeof (u_short)
  92. #else
  93. #define    RSLOP        0
  94. #endif
  95.  
  96. /*
  97.  * nextf[i] is the pointer to the next free block of size 2^(i+3).  The
  98.  * smallest allocatable block is 8 bytes.  The overhead information
  99.  * precedes the data area returned to the user.
  100.  */
  101. #define    NBUCKETS 30
  102. static    union overhead *nextf[NBUCKETS];
  103. extern    char *emptyblock();
  104.  
  105. static    int pagesz;            /* page size */
  106. static    int pagebucket;            /* page size bucket */
  107.  
  108. #ifdef MSTATS
  109. /*
  110.  * nmalloc[i] is the difference between the number of mallocs and frees
  111.  * for a given block size.
  112.  */
  113. static    u_int nmalloc[NBUCKETS];
  114. #include <stdio.h>
  115. #endif
  116.  
  117. #if defined(DEBUG) || defined(RCHECK)
  118. #define    ASSERT(p)   if (!(p)) botch("p")
  119. #include <stdio.h>
  120. static
  121. botch(s)
  122.     char *s;
  123. {
  124.     printf("\r\nassertion botched: %s\r\n", s);
  125.     abort();
  126. }
  127. #else
  128. #define    ASSERT(p)
  129. #endif
  130.  
  131. void *
  132. xmalloc(nbytes)
  133.     size_t nbytes;
  134. {
  135.       register union overhead *op;
  136.       register int bucket, n;
  137.     register unsigned amt;
  138.  
  139.     /*
  140.      * First time malloc is called, setup page size and
  141.      * align break pointer so all data will be page aligned.
  142.      */
  143.     if (pagesz == 0) {
  144.         pagesz = n = 4096;
  145.         bucket = 0;
  146.         amt = 8;
  147.         while (pagesz > amt) 
  148.             {
  149.             amt <<= 1;
  150.             bucket++;
  151.             }
  152.         pagebucket = bucket;
  153.     }
  154.     /*
  155.      * Convert amount of memory requested into closest block size
  156.      * stored in hash buckets which satisfies request.
  157.      * Account for space used per block for accounting.
  158.      */
  159.     if (nbytes <= (n = pagesz - sizeof (*op) - RSLOP)) {
  160. #ifndef RCHECK
  161.         amt = 8;    /* size of first bucket */
  162.         bucket = 0;
  163. #else
  164.         amt = 16;    /* size of first bucket */
  165.         bucket = 1;
  166. #endif
  167.         n = -(sizeof (*op) + RSLOP);
  168.     } else {
  169.         amt = pagesz;
  170.         bucket = pagebucket;
  171.     }
  172.     while (nbytes > amt + n) {
  173.         amt <<= 1;
  174.         if (amt == 0)
  175.             return (NULL);
  176.         bucket++;
  177.     }
  178.     /*
  179.      * If nothing in hash bucket right now,
  180.      * request more memory from the system.
  181.      */
  182.       if ((op = nextf[bucket]) == NULL) {
  183.           morecore(bucket);
  184.           if ((op = nextf[bucket]) == NULL)
  185.               return (NULL);
  186.     }
  187.     /* remove from linked list */
  188.       nextf[bucket] = op->ov_next;
  189.     op->ov_magic = MAGIC;
  190.     op->ov_index = bucket;
  191. #ifdef MSTATS
  192.       nmalloc[bucket]++;
  193. #endif
  194. #ifdef RCHECK
  195.     /*
  196.      * Record allocated size of block and
  197.      * bound space with magic numbers.
  198.      */
  199.     op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
  200.     op->ov_rmagic = RMAGIC;
  201.       *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
  202. #endif
  203.       return ((char *)(op + 1));
  204. }
  205.  
  206. /*
  207.  * Allocate more memory to the indicated bucket.
  208.  */
  209. static void
  210. morecore(bucket)
  211.     int bucket;
  212. {
  213.       register union overhead *op;
  214.     register int sz;        /* size of desired block */
  215.       int amt;            /* amount to allocate */
  216.       int nblks;            /* how many blocks we get */
  217.  
  218.     /*
  219.      * sbrk_size <= 0 only for big, FLUFFY, requests (about
  220.      * 2^30 bytes on a VAX, I think) or for a negative arg.
  221.      */
  222.     sz = 1 << (bucket + 3);
  223. #ifdef DEBUG
  224.     ASSERT(sz > 0);
  225. #else
  226.     if (sz <= 0)
  227.         return;
  228. #endif
  229.     if (sz < pagesz) {
  230.         amt = pagesz;
  231.           nblks = amt / sz;
  232.     } else {
  233.         amt = sz + pagesz;
  234.         nblks = 1;
  235.     }
  236.     op = (union overhead *)emptyblock(amt);
  237.     /* no more room! */
  238.       if ((int)op == -1)
  239.           return;
  240.     /*
  241.      * Add new memory allocated to that on
  242.      * free list for this hash bucket.
  243.      */
  244.       nextf[bucket] = op;
  245.       while (--nblks > 0) {
  246.         op->ov_next = (union overhead *)((caddr_t)op + sz);
  247.         op = (union overhead *)((caddr_t)op + sz);
  248.       }
  249. }
  250.  
  251. void
  252. free(cp)
  253.     void *cp;
  254. {   
  255.       register int size;
  256.     register union overhead *op;
  257.  
  258.       if (cp == NULL)
  259.           return;
  260.     op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
  261. #ifdef DEBUG
  262.       ASSERT(op->ov_magic == MAGIC);        /* make sure it was in use */
  263. #else
  264.     if (op->ov_magic != MAGIC)
  265.         return;                /* sanity */
  266. #endif
  267. #ifdef RCHECK
  268.       ASSERT(op->ov_rmagic == RMAGIC);
  269.     ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC);
  270. #endif
  271.       size = op->ov_index;
  272.       ASSERT(size < NBUCKETS);
  273.     op->ov_next = nextf[size];    /* also clobbers ov_magic */
  274.       nextf[size] = op;
  275. #ifdef MSTATS
  276.       nmalloc[size]--;
  277. #endif
  278. }
  279.  
  280. /*
  281.  * When a program attempts "storage compaction" as mentioned in the
  282.  * old malloc man page, it realloc's an already freed block.  Usually
  283.  * this is the last block it freed; occasionally it might be farther
  284.  * back.  We have to search all the free lists for the block in order
  285.  * to determine its bucket: 1st we make one pass thru the lists
  286.  * checking only the first block in each; if that fails we search
  287.  * ``realloc_srchlen'' blocks in each list for a match (the variable
  288.  * is extern so the caller can modify it).  If that fails we just copy
  289.  * however many bytes was given to realloc() and hope it's not huge.
  290.  */
  291. int realloc_srchlen = 4;    /* 4 should be plenty, -1 =>'s whole list */
  292.  
  293. void *
  294. realloc(cp, nbytes)
  295.     void *cp; 
  296.     size_t nbytes;
  297. {   
  298.       register u_int onb;
  299.     register int i;
  300.     union overhead *op;
  301.       char *res;
  302.     int was_alloced = 0;
  303.  
  304.       if (cp == NULL)
  305.           return (xmalloc(nbytes));
  306.     op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
  307.     if (op->ov_magic == MAGIC) {
  308.         was_alloced++;
  309.         i = op->ov_index;
  310.     } else {
  311.         /*
  312.          * Already free, doing "compaction".
  313.          *
  314.          * Search for the old block of memory on the
  315.          * free list.  First, check the most common
  316.          * case (last element free'd), then (this failing)
  317.          * the last ``realloc_srchlen'' items free'd.
  318.          * If all lookups fail, then assume the size of
  319.          * the memory block being realloc'd is the
  320.          * largest possible (so that all "nbytes" of new
  321.          * memory are copied into).  Note that this could cause
  322.          * a memory fault if the old area was tiny, and the moon
  323.          * is gibbous.  However, that is very unlikely.
  324.          */
  325.         if ((i = findbucket(op, 1)) < 0 &&
  326.             (i = findbucket(op, realloc_srchlen)) < 0)
  327.             i = NBUCKETS;
  328.     }
  329.     onb = 1 << (i + 3);
  330.     if (onb < pagesz)
  331.         onb -= sizeof (*op) + RSLOP;
  332.     else
  333.         onb += pagesz - sizeof (*op) - RSLOP;
  334.     /* avoid the copy if same size block */
  335.     if (was_alloced) {
  336.         if (i) {
  337.             i = 1 << (i + 2);
  338.             if (i < pagesz)
  339.                 i -= sizeof (*op) + RSLOP;
  340.             else
  341.                 i += pagesz - sizeof (*op) - RSLOP;
  342.         }
  343.         if (nbytes <= onb && nbytes > i) {
  344. #ifdef RCHECK
  345.             op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
  346.             *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
  347. #endif
  348.             return(cp);
  349.         } else
  350.             free(cp);
  351.     }
  352.       if ((res = xmalloc(nbytes)) == NULL)
  353.           return (NULL);
  354.       if (cp != res)        /* common optimization if "compacting" */
  355.         memcpy(res, cp, (nbytes < onb) ? nbytes : onb);
  356.       return (res);
  357. }
  358.  
  359. /*
  360.  * Search ``srchlen'' elements of each free list for a block whose
  361.  * header starts at ``freep''.  If srchlen is -1 search the whole list.
  362.  * Return bucket number, or -1 if not found.
  363.  */
  364. static
  365. findbucket(freep, srchlen)
  366.     union overhead *freep;
  367.     int srchlen;
  368. {
  369.     register union overhead *p;
  370.     register int i, j;
  371.  
  372.     for (i = 0; i < NBUCKETS; i++) {
  373.         j = 0;
  374.         for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
  375.             if (p == freep)
  376.                 return (i);
  377.             j++;
  378.         }
  379.     }
  380.     return (-1);
  381. }
  382.  
  383. #ifdef MSTATS
  384. /*
  385.  * mstats - print out statistics about malloc
  386.  * 
  387.  * Prints two lines of numbers, one showing the length of the free list
  388.  * for each size category, the second showing the number of mallocs -
  389.  * frees for each size category.
  390.  */
  391. mstats(s)
  392.     char *s;
  393. {
  394.       register int i, j;
  395.       register union overhead *p;
  396.       int totfree = 0,
  397.       totused = 0;
  398.  
  399.       kprintf("Memory allocation statistics %s\nfree:\t", s);
  400.       for (i = 0; i < NBUCKETS; i++) {
  401.           for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
  402.               ;
  403.           kprintf(" %d", j);
  404.           totfree += j * (1 << (i + 3));
  405.       }
  406.       kprintf("\nused:\t");
  407.       for (i = 0; i < NBUCKETS; i++) {
  408.           kprintf(" %d", nmalloc[i]);
  409.           totused += nmalloc[i] * (1 << (i + 3));
  410.       }
  411.       kprintf("\n\tTotal in use: %d, total free: %d\n",
  412.         totused, totfree);
  413. }
  414. #endif
  415.